package com.caiheng.api.controller.estate;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.lock.LockInfo;
import com.baomidou.lock.LockTemplate;
import com.baomidou.lock.executor.RedissonLockExecutor;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caiheng.api.constant.ResponseCode;
import com.caiheng.api.controller.platform.BaseController;
import com.caiheng.api.entity.estate.*;
import com.caiheng.api.entity.sys.SysUser;
import com.caiheng.api.entity.wxuser.User;
import com.caiheng.api.service.estate.*;
import com.caiheng.api.service.platfom.WxTemplateService;
import com.caiheng.api.service.sys.SysUserService;
import com.caiheng.api.service.wxuser.UserService;
import com.caiheng.api.util.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 *@Author: ZhouWei
 *@Description:  报修记录
 *@Date 2018-05-10
 */
@Component
@RestController
@RequestMapping("/customer/call/record")//url:模块/资源/{}/细分
public class CustomerCallRecordController extends BaseController {

    @Resource
    private UserService userService;
    @Resource
    private EstateRoomService estateRoomService;
    @Resource
    private EstateService estateService;
    @Resource
    private EstateUserService estateUserService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private EstateCustomerCallRecordService estateCustomerCallRecordService;
    @Resource
    private EstateCustomerCallRecordImgService customerCallRecordImgService;

    @Resource
    protected RedisTemplate<String, Object> redisTemplate;
    @Resource
    private LockTemplate lockTemplate;

    @Value("${web.uploadPath}")
    private String uploadPath;//图片地址

    @Value("${web.imgPrefixOss}")
    private String imgPrefix;//图片地址


    /**
     * 客服呼叫信息
     * @param
     * @throws Exception
     */
    @PostMapping(value="/detail")
    public JSONObject detail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "customer/call/record/detail 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int record_id = jsonRequest.containsKey("record_id") ? jsonRequest.getInt("record_id") : 0;

            EstateCustomerCallRecord callRecord = null;//estateCustomerCallRecordService.getRepairById(record_id);
            if(callRecord == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该报修工单不存在"),true,true);
            }

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功", callRecord),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 上报
     * @param
     * @throws Exception
     */
    @PostMapping(value="/add")
    public JSONObject addRecord(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();

        logBefore(logger, "customer/call/record/add 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
        JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
        int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;

        final LockInfo lockInfo = lockTemplate.lock(user_id + "_addCallRecord_" + user_id, 30000L, 5000L, RedissonLockExecutor.class);
        if (lockInfo == null) {
            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"业务处理中,请稍后再试"),true,true);
        }

        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            int room_id = jsonRequest.containsKey("room_id") ? jsonRequest.getInt("room_id") : 0;
            String phone_num = jsonRequest.containsKey("phone_num") ? jsonRequest.getStr("phone_num") : null;
            String remark = jsonRequest.containsKey("remark") ? jsonRequest.getStr("remark") : null;


            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }


            EstateCustomerCallRecord callRecord = new EstateCustomerCallRecord();


            EstateUser estateUser = estateUserService.getEstateUser(user_id);
            if(estateUser!= null){
                callRecord.setSysUserId(estateUser.getSysUserId());
                SysUser sysUser = sysUserService.findById(estateUser.getSysUserId());
                if(sysUser!= null){
                    callRecord.setSysUserName(sysUser.getUserName());
                }
            }

            EstateRoom room = estateRoomService.findById(room_id);
            if(room != null){
                callRecord.setEstateId(room.getEstateId());
                Estate estate = estateService.findById(room.getEstateId());
                if(estate!= null){
                    callRecord.setEstateName(estate.getEstateName());
                }

                callRecord.setCallPhone(room.getPhoneNum());
                callRecord.setRoomNo(room.getRoomNo());
                callRecord.setRoomRealName(room.getRealName());
            }

            callRecord.setRoomId(room_id);
            callRecord.setWxUserId(user_id);
            callRecord.setCallTime(new Date());
            callRecord.setRemark(remark);
            callRecord.setState(0);

            boolean ret = estateCustomerCallRecordService.save(callRecord);
            if(ret){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"上报成功"),true,true);
            }else {
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }finally {
            //释放锁
            lockTemplate.releaseLock(lockInfo);
        }
        return result;
    }



    /**
     * 修改信息：提交其他信息，备注、截图等
     * @param
     * @throws Exception
     */
    @PostMapping(value="/update")
    public JSONObject updateRecord(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();

        logBefore(logger, "customer/call/record/update 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
        JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
        int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;

        final LockInfo lockInfo = lockTemplate.lock(user_id + "_updateCallRecord_" + user_id, 30000L, 5000L, RedissonLockExecutor.class);
        if (lockInfo == null) {
            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"业务处理中,请稍后再试"),true,true);
        }

        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            int record_id = jsonRequest.containsKey("record_id") ? jsonRequest.getInt("record_id") : 0;
            int state = jsonRequest.containsKey("state") ? jsonRequest.getInt("state") : 0;
            String remark = jsonRequest.containsKey("remark") ? jsonRequest.getStr("remark") : null;


            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            EstateCustomerCallRecord callRecord = estateCustomerCallRecordService.getById(record_id);
            if(callRecord == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该记录不存在"),true,true);
            }


            EstateUser estateUser = estateUserService.getEstateUser(user_id);
            if(estateUser!= null){
                callRecord.setSysUserId(estateUser.getSysUserId());
                SysUser sysUser = sysUserService.findById(estateUser.getSysUserId());
                if(sysUser!= null){
                    callRecord.setSysUserName(sysUser.getUserName());
                }
            }
            callRecord.setRemark(remark);
            callRecord.setState(state);

            boolean ret = estateCustomerCallRecordService.updateById(callRecord);
            if(ret){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"上报成功"),true,true);
            }else {
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"上报失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }finally {
            //释放锁
            lockTemplate.releaseLock(lockInfo);
        }
        return result;
    }


    /**
     * 我的上报列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/list")
    public JSONObject recordList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "customer/call/record/list 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int state = jsonRequest.containsKey("state") ? jsonRequest.getInt("state") : -1;
            int room_id = jsonRequest.containsKey("room_id") ? jsonRequest.getInt("room_id") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex")&& StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString()) ? jsonRequest.getInt("pageIndex") : 0;
            int pageSize = jsonRequest.containsKey("pageSize")&& StrUtil.isNotEmpty(jsonRequest.get("pageSize").toString()) ? jsonRequest.getInt("pageSize") : 20;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            EstateRoom room = estateRoomService.findById(room_id);
            if(room == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该房间不存在"),true,true);
            }

            QueryWrapper<EstateCustomerCallRecord> qw = new QueryWrapper<>();
            qw.eq("wx_user_id", user_id);
            if(state > -1){
                qw.eq("state", state);
            }
            qw.eq("room_id", room_id);
            qw.orderByDesc("call_time");
            List<EstateCustomerCallRecord> list = estateCustomerCallRecordService.getPageEntityList(qw, pageIndex,pageSize);
            for (EstateCustomerCallRecord record : list) {

                List<String> imgListArray = new ArrayList<>();
                List<EstateCustomerCallRecordImg> imgList = customerCallRecordImgService.list(new QueryWrapper<EstateCustomerCallRecordImg>().eq("record_id", record.getId()));
                if(CollUtil.isNotEmpty(imgList)){
                    for (EstateCustomerCallRecordImg img : imgList) {
                        imgListArray.add(imgPrefix + img.getImgUrl());
                    }
                    record.setRecordImgList(imgListArray);
                }

            }
            map.put("recordList", list);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(), map),false,false);

        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 报修记录的图片上传
     * @param
     * @throws Exception
     */
    @PostMapping(value="/uploadImg")
    public JSONObject uploadImg(@RequestParam("record_id") int record_id, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            EstateCustomerCallRecord record = estateCustomerCallRecordService.getById(record_id);
            if(record == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "记录不存在"), true, true);
            }
            System.out.println("record_id==" + record_id);

            // 创建一个通用的多部分解析器.
            CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            // 设置编码
            commonsMultipartResolver.setDefaultEncoding("utf-8");
            // 判断是否有文件上传
            if (commonsMultipartResolver.isMultipart(request)) {//有文件上传
                //将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
                //获取multiRequest 中所有的文件名
                Iterator<String> iter = multiRequest.getFileNames();
                if (iter.hasNext()) {
                    Map<String, MultipartFile> maps = multiRequest.getFileMap();

                    String imgs = "";
                    for(String key : maps.keySet()) {
                        MultipartFile certurl = maps.get(key);
                        if (!certurl.isEmpty()) {
                            String prefix = certurl.getOriginalFilename().substring(certurl.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();
                            if ("jpeg".equals(prefix) || "jpg".equals(prefix) || "png".equals(prefix) || "mp4".equals(prefix)) {
                                String fileName = "record_img_" + new Date().getTime() + "." + prefix;// user_photo.getOriginalFilename();
                                try {
                                    byte[] byteImg = certurl.getBytes();
                                    if (byteImg != null) {
                                        //上传头像到OSS
                                        int upload_type = OssUtil.TYPE_CALL_RECORD_PHOTOS;

                                        String img_key = OssUtil.getUploadPrefix(upload_type) + DateUtil.getMonthStr(new Date()) + "/" + fileName;

                                        String filePath1 = OssUtil.getUploadPrefix(upload_type) + DateUtil.getMonthStr(new Date());
                                        File file = new File(uploadPath + filePath1);
                                        if(!file.exists()){
                                            file.mkdirs();
                                        }

                                        String filePath = uploadPath + img_key;
                                        FileOutputStream out = new FileOutputStream(filePath);
                                        out.write(certurl.getBytes());
                                        out.flush();
                                        out.close();
                                        ImagesFiler.imageResize(filePath,filePath);

                                        OssUtil.uploadObs(certurl.getInputStream(), DateUtil.getMonthStr(new Date()) + "/" + fileName,upload_type);

                                        EstateCustomerCallRecordImg img = new EstateCustomerCallRecordImg();
                                        img.setImgUrl(img_key);
                                        img.setRecordId(record_id);
                                        img.setCreateTime(new Date());
                                        img.setFileType(prefix);
                                        customerCallRecordImgService.save(img);

                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
            }
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "图片上传成功"), true, true);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
        }
        return result;
    }

}
